from loguru import logger
from flask import request, Blueprint
from dao.models import User
from dao.schemas.user_schema import UserOutSchema
from dao import db
from entity.base_response import model_to_dicts, json

user_view = Blueprint('user', __name__, url_prefix='/user')


@user_view.route("/list")
def user():
    """
    错误捕获测试
    """
    user_model = User.query.all()
    logger.info("数据库查询结果", user_model)
    return json(data=model_to_dicts(schema=UserOutSchema, data=user_model), count=len(user_model))


@user_view.route("/add", methods=['GET', 'POST'])
def user_add():
    """
    错误捕获测试
    """
    req_json = request.json
    name = req_json.get("name")
    age = req_json.get("age")
    status = req_json.get("status")
    user_model = User(name=name, age=age, status=status)

    db.session.add(user_model)
    db.session.commit()
    logger.info("数据库查询结果", user_model)
    return json(data=model_to_dicts(schema=UserOutSchema, data=user_model, many=False))
